package test;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.DomElement;
import com.gargoylesoftware.htmlunit.html.DomNodeList;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import sziit.znk.utils.importothers.FileDownload;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Iterator;
import java.util.List;

public class DownloadFileFromJD {

    int i = 0;

    public void downloadFileFromJD(String url) throws Exception {
        WebClient webClient = new WebClient(BrowserVersion.CHROME);
        webClient.getOptions().setCssEnabled(false);
        webClient.getOptions().setJavaScriptEnabled(false);
        try {
            HtmlPage page = webClient.getPage(url);
//            List<HtmlElement> J_bottomPage = page.getByXPath("//div[@id='J_bottomPage']");
//            DomNodeList<DomElement> a = page.getElementsByTagName("a");
//            for (int i1 = 0; i1 < a.size(); i1++) {
//                if (a.get(i1).getAttribute("class").equals("fp-next")){
//
//                }
//            }



            i = 0;
            FileDownload fileDownload = new FileDownload();
            List<HtmlElement> lis = page.getByXPath("//div[@id='J_goodsList']/ul[@class='gl-warp clearfix']/li");
            for (HtmlElement li : lis) {
                List<HtmlElement> imgs = li.getByXPath("div/div[@class='p-img']/a/img");
                Iterator<HtmlElement> iterator = imgs.iterator();
                while (iterator.hasNext()) {
                    HtmlElement img = iterator.next();
                    String imgUrl = img.getAttribute("data-lazy-img");
                    System.out.println("src = " + imgUrl);
                    String str = Integer.toString(i);
                    String fileName = " temp" + str + ".jpg";
                    ++i;
                    fileDownload.saveFile("http:" + imgUrl,"photo1","GET" , fileName);
                    System.out.println("ok" + "\n");
                }
            }

        } catch (FailingHttpStatusCodeException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            webClient.close();
        }
    }

    public void nextUrl() {

    }

}
